package com.learning.netease.io.bio;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * ClassName: BIOServer
 * Description: 服务端
 * Date: 2021/1/10 22:33 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Slf4j
public class BioServer {

    public static void main(String[] args) throws Exception {
        try (ServerSocket serverSocket = new ServerSocket(8080)) {
            log.info("~~ 服务器启动成功 ~~");
            while (!serverSocket.isClosed()) {
                // 阻塞方法
                Socket request = serverSocket.accept();
                log.info("收到新连接 : {}", request.toString());

                // 接收数据、打印。net + i/o
                InputStream inputStream = request.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                String msg;
                // 没有数据，会在这里阻塞
                // 【重要】多个客户端访问，只有等第一个客户端结束，才会接受第二个客户端的数据
                while ((msg = reader.readLine()) != null) {
                    if (msg.length() == 0) {
                        break;
                    }
                    log.info(msg);
                }
                log.info("收到数据,来自：{}", request.toString());
            }
        }
    }
}
